package com.ruoyi.mqtt.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.mqtt.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.ruoyi.mqtt.handler.MqttMessageHandler;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class NettyMqttClientManager {

    @Value("${mqtt.broker-url}")
    private String brokerUrl;

    @Value("${mqtt.client-count:8}")
    private int clientCount;

    @Value("${mqtt.topic}")
    private String topic;

    @Value("${mqtt.retry.max-attempts:3}")
    private int maxRetryAttempts;

    @Value("${mqtt.retry.delay:5000}")
    private long retryDelay;

    private final EventLoopGroup workerGroup = new NioEventLoopGroup();
    private final List<Channel> channels = new ArrayList<>();
    private final MqttMessageHandler messageHandler;

    public NettyMqttClientManager(MqttMessageHandler messageHandler) {
        this.messageHandler = messageHandler;
    }

    @PostConstruct
    public void init() throws Exception {
        int attempts = 0;
        while (attempts < maxRetryAttempts) {
            try {
                connectMqtt();
                log.info("Successfully connected to MQTT broker");
                return;
            } catch (Exception e) {
                attempts++;
                if (attempts < maxRetryAttempts) {
                    log.warn("Failed to connect to MQTT broker, attempt {}/{}. Retrying in {} ms...",
                        attempts, maxRetryAttempts, retryDelay);
                    try {
                        Thread.sleep(retryDelay);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                } else {
                    log.error("Failed to connect to MQTT broker after {} attempts", maxRetryAttempts);
                    throw e;
                }
            }
        }
    }

    @PreDestroy
    public void destroy() {
        for (Channel channel : channels) {
            channel.close();
        }
        workerGroup.shutdownGracefully();
    }

    private void connectMqtt() throws Exception {
        String host = brokerUrl.split("://")[1].split(":")[0];
        int port = Integer.parseInt(brokerUrl.split("://")[1].split(":")[1]);

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("mqtt-decoder", new MqttDecoder());
                        pipeline.addLast("mqtt-encoder", MqttEncoder.INSTANCE);
                        pipeline.addLast("mqtt-handler", new MqttChannelHandler(messageHandler));
                    }
                });

        for (int i = 0; i < clientCount; i++) {
            String clientId = "netty-mqtt-client-" + i;
            Channel channel = bootstrap.connect(host, port).sync().channel();

            MqttConnectMessage connectMessage = MqttMessageBuilders.connect()
                    .clientId(clientId)
                    .cleanSession(true)
                    .build();
            channel.writeAndFlush(connectMessage);

            String sharedTopic = "$share/group/" + topic;
            MqttSubscribeMessage subscribeMessage = MqttMessageBuilders.subscribe()
                    .messageId(1)
                    .addSubscription(MqttQoS.AT_MOST_ONCE, sharedTopic)
                    .build();
            channel.writeAndFlush(subscribeMessage);

            channels.add(channel);
            log.info("MQTT客户端 {} 已连接并订阅主题: {}", clientId, sharedTopic);
        }
    }
}
